class D:
    def __init__(self, name):
        self.name = name

    def __del__(self):
        # 尽量不用全局变量，因为会破坏命名空间
        global x
        # 在对象销毁前，赋值给一个全局变量
        x = self


d = D("小甲鱼")
print(d)  # <__main__.D object at 0x105800fd0>
print(d.name)  # 小甲鱼

del d
# print(d)      # NameError: name 'd' is not defined

print(x)  # <__main__.D object at 0x105b60fd0> 其实还是存在的
print(x.name)  # 小甲鱼

print("=" * 200)


class E:
    def __init__(self, name, func):
        self.name = name
        self.func = func

    def __del__(self):
        # 在对象销毁前，把对象通过参数的形式传递给函数
        self.func(self)


def outer():
    x = 0

    def inner(y=None):
        nonlocal x
        if y:
            x = y
        else:
            return x

    return inner


f = outer()
e = E("小甲鱼", f)
print(e)  # <__main__.E object at 0x107d56730>
print(e.name)  # 小甲鱼

del e  # 小甲鱼

# print(e)

g = f()
print(g)  # <__main__.E object at 0x107d56730>
print(g.name)  # 小甲鱼
